/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.scripting.xmltags;

import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;

/**
 * @author Clinton Begin
 */
public class DynamicSqlSource implements SqlSource {

  private final Configuration configuration;
  private final SqlNode rootSqlNode;

  public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) {
    this.configuration = configuration;
    this.rootSqlNode = rootSqlNode;
  }

  @Override
  public BoundSql getBoundSql(Object parameterObject) {
    DynamicContext context = new DynamicContext(configuration, parameterObject);
    /**
     * 处理sql最终sql处理成这样，如下：
     * select id, user_name, password
     *      from t_user t
     *      WHERE t.user_name = #{userName}
     *      and id in
     *      (
     *      #{__frch_id_0}
     *      ,
     *      #{__frch_id_1}
     *      )
     */
    rootSqlNode.apply(context);
    //创建sql解析
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    //获取参数类型
    Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
    /**
     * context.getBindings() 这个是参数绑定包，里面是存储你填写参数的真正值
     * 解析sql的#{}，SQL最终变成这样，如下：
     * select id, user_name, password
     *         from t_user t
     *          WHERE t.user_name = ?
     *                 and id in (?,?)
     */
    SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());

    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    //把参数映射放到sql包中的additionalParameters对象，
    // 在sql设置参数中针对foreach的参数处理，就是在additionalParameters这个对象获取
    context.getBindings().forEach(boundSql::setAdditionalParameter);
    return boundSql;
  }

}
